#!/usr/bin/env python2

import os
import sys
import glob
import shutil
import argparse
import subprocess
import platform
import time
import string
import signal

cwd = os.path.dirname(os.path.abspath(__file__))
gopath = os.getenv("GOPATH")
pathcommon = os.path.join(gopath, "src/mae_proj/MAE/common")

#need prebuild path
preBuildPath = [cwd,pathcommon]




def build():

    if os.system("go build -v") != 0:
        sys.exit(1)




def afterbuild():
    for path in preBuildPath:
        for d,fd,fl in os.walk(path):
            for f in fl:
                sufix = os.path.splitext(f)[1][1:]
                if sufix == "go":
                     os.remove(d + '/' + f)
        for d,fd,fl in os.walk(path):
            for f in fl:
                pre,sufix = os.path.splitext(f)
                sufix = sufix[1:]
                if sufix == "goo":
                     os.rename(d + '/' + f,d+'/'+pre+".go")

def prebuild ():
    for path in preBuildPath:
        for d,fd,fl in os.walk(path):
            for f in fl:
                sufix = os.path.splitext(f)[1][1:]
                if sufix == "go":
                     dealfile(d + '/' + f,f)

def dealfile(filepath,filename):
    print "deal file:"+filepath
    strgrep1 = "Error(\""
    strgrep2 = "Debug(\""
    strgrep3 = "Info(\""
    strgrep4 = "Warning(\""
    filenameTmp = filepath+"o"
    os.rename(filepath,filenameTmp)
    input   = open(filenameTmp)
    lines   = input.readlines()
    input.close()

    output  = open(filepath,'w')
    lineNum = 0
    for line in lines:
        if not line:
            break
        lineNum += 1
        if strgrep1 in line  :
            temp    = line.split(strgrep1)
            temp1   = temp[0] +strgrep1+"["+ filename+":"+str(lineNum)+"]," + temp[1]
            #print temp
            #print temp1
            output.write(temp1)
        elif strgrep2 in line  :
            temp    = line.split(strgrep2)
            temp1   = temp[0] +strgrep2+"["+ filename+":"+str(lineNum)+"]," + temp[1]
            output.write(temp1)
        elif strgrep3 in line  :
            temp    = line.split(strgrep3)
            temp1   = temp[0] +strgrep3+"["+ filename+":"+str(lineNum)+"]," + temp[1]
            output.write(temp1)
        elif strgrep4 in line  :
            temp    = line.split(strgrep4)
            temp1   = temp[0] +strgrep4+"["+ filename+":"+str(lineNum)+"]," + temp[1]
            output.write(temp1)
        else:
            output.write(line)
    output.close()




prog = os.path.basename(os.path.abspath(__file__))
parser = argparse.ArgumentParser(prog="./%s" % prog)
parser.add_argument("-l", "--log", action="store_true", dest="log", help="build with better log info")
opts = parser.parse_args()



signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
prebuild()
try:
    build()
finally:
    afterbuild()
